package com.ruoyi.drone.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.drone.domain.DroneUserProfile;
import com.ruoyi.drone.domain.DroneOrganization;
import com.ruoyi.drone.mapper.DroneUserProfileMapper;
import com.ruoyi.drone.mapper.DroneOrganizationMapper;
import com.ruoyi.drone.service.IDroneUserProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户身份相关接口
 */
@RestController
@RequestMapping("/drone/user")
public class DroneUserController extends BaseController {

    @Autowired
    private DroneUserProfileMapper droneUserProfileMapper;

    @Autowired
    private DroneOrganizationMapper droneOrganizationMapper;

    @Autowired
    private IDroneUserProfileService droneUserProfileService;

    /**
     * 获取当前用户的身份信息
     */
    @GetMapping("/identity")
    public AjaxResult getUserIdentity(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return AjaxResult.error("未登录或用户信息缺失");
        }

        Map<String, Object> identity = new HashMap<>();
        
        // 检查是否为飞手
        DroneUserProfile pilotProfile = droneUserProfileMapper.selectDroneUserProfileByUserId(userId);
        if (pilotProfile != null) {
            identity.put("isPilot", true);
            identity.put("pilotStatus", pilotProfile.getStatus());
            identity.put("pilotProfile", pilotProfile);
        } else {
            identity.put("isPilot", false);
        }

        // 检查是否为组织方
        DroneOrganization organization = droneOrganizationMapper.selectDroneOrganizationByUserId(userId);
        if (organization != null) {
            identity.put("isOrganization", true);
            identity.put("orgStatus", organization.getStatus());
            identity.put("organization", organization);
        } else {
            identity.put("isOrganization", false);
        }

        // 判断用户类型
        if (pilotProfile != null && organization != null) {
            identity.put("userType", "both"); // 既是飞手又是组织方
        } else if (pilotProfile != null) {
            identity.put("userType", "pilot"); // 只是飞手
        } else if (organization != null) {
            identity.put("userType", "organization"); // 只是组织方
        } else {
            identity.put("userType", "none"); // 都没有注册
        }

        return AjaxResult.success("获取身份信息成功", identity);
    }

    /**
     * 检查用户是否为飞手（用于接单权限验证）
     */
    @GetMapping("/isPilot")
    public AjaxResult isPilot(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return AjaxResult.error("未登录或用户信息缺失");
        }

        DroneUserProfile pilotProfile = droneUserProfileMapper.selectDroneUserProfileByUserId(userId);
        if (pilotProfile == null) {
            return AjaxResult.success(false);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("isPilot", true);
        result.put("status", pilotProfile.getStatus());
        result.put("canAcceptTask", "1".equals(pilotProfile.getStatus())); // 只有审核通过的飞手才能接单

        return AjaxResult.success(result);
    }

    /**
     * 检查用户是否为组织方（用于发布任务权限验证）
     */
    @GetMapping("/isOrganization")
    public AjaxResult isOrganization(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return AjaxResult.error("未登录或用户信息缺失");
        }

        DroneOrganization organization = droneOrganizationMapper.selectDroneOrganizationByUserId(userId);
        if (organization == null) {
            return AjaxResult.success(false);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("isOrganization", true);
        result.put("status", organization.getStatus());
        result.put("canPublishTask", "1".equals(organization.getStatus())); // 只有审核通过的组织方才能发布任务

        return AjaxResult.success(result);
    }

    /**
     * 查询飞手档案列表
     */
    @GetMapping("/pilot/list")
    public TableDataInfo list(DroneUserProfile droneUserProfile) {
        startPage();
        List<DroneUserProfile> list = droneUserProfileService.selectDroneUserProfileList(droneUserProfile);
        return getDataTable(list);
    }

    /**
     * 获取飞手档案详细信息
     */
    @GetMapping(value = "/pilot/{profileId}")
    public AjaxResult getInfo(@PathVariable("profileId") Long profileId) {
        return success(droneUserProfileService.selectDroneUserProfileByProfileId(profileId));
    }

    /**
     * 新增飞手档案
     */
    @PostMapping("/pilot")
    public AjaxResult add(@RequestBody DroneUserProfile droneUserProfile) {
        return toAjax(droneUserProfileService.insertDroneUserProfile(droneUserProfile));
    }

    /**
     * 修改飞手档案
     */
    @PutMapping("/pilot")
    public AjaxResult edit(@RequestBody DroneUserProfile droneUserProfile) {
        return toAjax(droneUserProfileService.updateDroneUserProfile(droneUserProfile));
    }

    /**
     * 删除飞手档案
     */
    @DeleteMapping("/pilot/{profileIds}")
    public AjaxResult remove(@PathVariable Long[] profileIds) {
        return toAjax(droneUserProfileService.deleteDroneUserProfileByProfileIds(profileIds));
    }

    /**
     * 审核飞手档案
     */
    @PutMapping("/pilot/audit")
    public AjaxResult audit(@RequestBody DroneUserProfile droneUserProfile) {
        return toAjax(droneUserProfileService.updateDroneUserProfile(droneUserProfile));
    }

    /**
     * 获取热门飞手列表（只返回审核通过的前5个飞手）
     */
    @GetMapping("/pilot/hot")
    public AjaxResult getHotPilots() {
        DroneUserProfile query = new DroneUserProfile();
        query.setStatus("1"); // 只查询审核通过的飞手（1=已通过）
        
        List<DroneUserProfile> list = droneUserProfileService.selectDroneUserProfileList(query);
        
        // 只返回前5个
        List<DroneUserProfile> hotList = list.size() > 5 ? list.subList(0, 5) : list;
        
        return AjaxResult.success("获取热门飞手成功", hotList);
    }
}
